import java.sql.*;
import java.util.*;

public class CinemaSystem {

    private static Connection conn;

    // 主方法
    public static void main(String[] args) {
        try {
            conn = DriverManager.getConnection("jdbc:sqlite:cinema_system.db");  // SQLite数据库连接
            createTables();  // 创建表
            initAdmin();     // 初始化管理员
            run();           // 启动系统
        } catch (SQLException e) {
            System.err.println("Database connection failed: " + e.getMessage());
        }
    }

    // 初始化默认管理员
    public static void initAdmin() {
        try (PreparedStatement stmt = conn.prepareStatement(
                "INSERT OR IGNORE INTO users(username,password,role,phone) VALUES('admin','ynuinfo#777','admin','13800138000')")) {
            stmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("初始化管理员失败: " + e.getMessage());
        }
    }

    // 启动系统，显示主菜单
    public static void run() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("\n--- 影院管理系统 ---");
            System.out.println("1. 登录");
            System.out.println("2. 退出");
            String choice = sc.nextLine();
            switch (choice) {
                case "1":
                    login();  // 用户登录
                    break;
                case "2":
                    System.out.println("退出系统！");
                    return;
                default:
                    System.out.println("无效选择！");
            }
        }
    }

    // 登录功能
    public static void login() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名: ");
        String username = sc.nextLine();
        System.out.print("请输入密码: ");
        String password = sc.nextLine();

        try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?")) {
            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                String role = rs.getString("role");
                System.out.println("登录成功！ 角色：" + role);
                switch (role) {
                    case "admin":   adminMenu();   break;
                    case "manager": managerMenu(); break;
                    case "cashier": cashierMenu(); break;
                    default:        System.out.println("无效角色！");
                }
            } else {
                System.out.println("用户名或密码错误！");
            }
        } catch (SQLException e) {
            System.err.println("登录失败: " + e.getMessage());
        }
    }

    // ------------------ 管理员菜单 ------------------
    public static void adminMenu() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("\n--- 管理员菜单 ---");
            System.out.println("1. 查看所有用户");
            System.out.println("2. 重置用户密码");
            System.out.println("3. 删除用户");
            System.out.println("4. 增加用户");
            System.out.println("5. 修改用户信息");
            System.out.println("0. 退出");
            String choice = sc.nextLine();
            switch (choice) {
                case "1": listUsers(); break;
                case "2": resetPassword(); break;
                case "3": deleteUser(); break;
                case "4": addUser(); break;
                case "5": modifyUser(); break;
                case "0": return;
                default:  System.out.println("无效选择！");
            }
        }
    }

    // ------------------ 经理菜单 ------------------
    public static void managerMenu() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("\n--- 经理菜单 ---");
            System.out.println("1. 添加影片");
            System.out.println("2. 修改影片");
            System.out.println("3. 删除影片");
            System.out.println("4. 查看影片");
            System.out.println("5. 增加排片");
            System.out.println("6. 查看排片");
            System.out.println("0. 退出");
            String choice = sc.nextLine();
            switch (choice) {
                case "1": addMovie(); break;
                case "2": modifyMovie(); break;
                case "3": deleteMovie(); break;
                case "4": listMovies(); break;
                case "5": addSchedule(); break;
                case "6": listSchedules(); break;
                case "0": return;
                default:  System.out.println("无效选择！");
            }
        }
    }

    // ------------------ 前台菜单 ------------------
    public static void cashierMenu() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("\n--- 前台菜单 ---");
            System.out.println("1. 查看影片");
            System.out.println("2. 查看排片");
            System.out.println("3. 售票");
            System.out.println("4. 退票");
            System.out.println("0. 退出");
            String choice = sc.nextLine();
            switch (choice) {
                case "1": listMovies(); break;
                case "2": listSchedules(); break;
                case "3": sellTicket(); break;
                case "4": refundTicket(); break;
                case "0": return;
                default:  System.out.println("无效选择！");
            }
        }
    }

    // ------------------ 管理员功能实现 ------------------
    public static void listUsers() {
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {
            while (rs.next()) {
                System.out.println("用户ID: " + rs.getInt("id") + ", 用户名: " + rs.getString("username") +
                        ", 角色: " + rs.getString("role") + ", 手机号: " + rs.getString("phone"));
            }
        } catch (SQLException e) {
            System.err.println("查询用户失败: " + e.getMessage());
        }
    }

    public static void resetPassword() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要重置密码的用户名: ");
        String username = sc.nextLine();
        try (PreparedStatement stmt = conn.prepareStatement("UPDATE users SET password = '123456' WHERE username = ?")) {
            stmt.setString(1, username);
            stmt.executeUpdate();
            System.out.println("密码重置成功！");
        } catch (SQLException e) {
            System.err.println("重置密码失败: " + e.getMessage());
        }
    }

    public static void deleteUser() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要删除的用户名: ");
        String username = sc.nextLine();
        if (username.equals("admin")) {
            System.out.println("不能删除管理员账户！");
            return;
        }
        try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM users WHERE username = ?")) {
            stmt.setString(1, username);
            stmt.executeUpdate();
            System.out.println("用户删除成功！");
        } catch (SQLException e) {
            System.err.println("删除用户失败: " + e.getMessage());
        }
    }

    public static void addUser() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名: ");
        String username = sc.nextLine();
        System.out.print("请输入角色 (admin/manager/cashier): ");
        String role = sc.nextLine();
        System.out.print("请输入手机号: ");
        String phone = sc.nextLine();
        String password = "123456";  // 默认密码
        try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO users (username, password, role, phone) VALUES (?, ?, ?, ?)")) {
            stmt.setString(1, username);
            stmt.setString(2, password);
            stmt.setString(3, role);
            stmt.setString(4, phone);
            stmt.executeUpdate();
            System.out.println("用户添加成功！");
        } catch (SQLException e) {
            System.err.println("添加用户失败: " + e.getMessage());
        }
    }

    public static void modifyUser() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要修改的用户名: ");
        String username = sc.nextLine();
        System.out.print("修改角色 (manager/cashier): ");
        String newRole = sc.nextLine();
        System.out.print("修改手机号: ");
        String newPhone = sc.nextLine();
        try (PreparedStatement stmt = conn.prepareStatement("UPDATE users SET role = ?, phone = ? WHERE username = ?")) {
            stmt.setString(1, newRole);
            stmt.setString(2, newPhone);
            stmt.setString(3, username);
            stmt.executeUpdate();
            System.out.println("用户信息修改成功！");
        } catch (SQLException e) {
            System.err.println("修改用户信息失败: " + e.getMessage());
        }
    }

    // ------------------ 经理功能实现 ------------------
    public static void addMovie() {
        Scanner sc = new Scanner(System.in);
        System.out.print("片名: "); String name = sc.nextLine();
        System.out.print("导演: "); String director = sc.nextLine();
        System.out.print("主演: "); String actor = sc.nextLine();
        System.out.print("简介: "); String desc = sc.nextLine();
        System.out.print("时长: "); int duration = Integer.parseInt(sc.nextLine());
        System.out.print("评分: "); double rating = Double.parseDouble(sc.nextLine());
        try (PreparedStatement stmt = conn.prepareStatement(
                "INSERT INTO movies(name,director,actor,description,duration,rating) VALUES(?,?,?,?,?,?)")) {
            stmt.setString(1, name);
            stmt.setString(2, director);
            stmt.setString(3, actor);
            stmt.setString(4, desc);
            stmt.setInt(5, duration);
            stmt.setDouble(6, rating);
            stmt.executeUpdate();
            System.out.println("影片添加成功！");
        } catch (SQLException e) {
            System.err.println("添加影片失败: " + e.getMessage());
        }
    }

    public static void listMovies() {
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM movies")) {
            while (rs.next()) {
                System.out.println("影片ID:" + rs.getInt("id") + ", 名称:" + rs.getString("name") +
                        ", 导演:" + rs.getString("director") + ", 主演:" + rs.getString("actor") +
                        ", 时长:" + rs.getInt("duration") + "分钟, 评分:" + rs.getDouble("rating"));
            }
        } catch (SQLException e) {
            System.err.println("查询影片失败: " + e.getMessage());
        }
    }

    public static void modifyMovie() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要修改的影片ID: ");
        int id = Integer.parseInt(sc.nextLine());
        System.out.print("新片名: "); String name = sc.nextLine();
        try (PreparedStatement stmt = conn.prepareStatement("UPDATE movies SET name=? WHERE id=?")) {
            stmt.setString(1, name);
            stmt.setInt(2, id);
            stmt.executeUpdate();
            System.out.println("影片修改成功！");
        } catch (SQLException e) {
            System.err.println("修改影片失败: " + e.getMessage());
        }
    }

    public static void deleteMovie() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要删除的影片ID: ");
        int id = Integer.parseInt(sc.nextLine());
        try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM movies WHERE id=?")) {
            stmt.setInt(1, id);
            stmt.executeUpdate();
            System.out.println("影片删除成功！");
        } catch (SQLException e) {
            System.err.println("删除影片失败: " + e.getMessage());
        }
    }

    public static void addSchedule() {
        Scanner sc = new Scanner(System.in);
        System.out.print("影片ID: "); int movieId = Integer.parseInt(sc.nextLine());
        System.out.print("影厅: "); String hall = sc.nextLine();
        System.out.print("时间: "); String time = sc.nextLine();
        System.out.print("票价: "); double price = Double.parseDouble(sc.nextLine());
        System.out.print("总座位数: "); int total = Integer.parseInt(sc.nextLine());
        try (PreparedStatement stmt = conn.prepareStatement(
                "INSERT INTO schedules(movie_id,hall,time,price,total_seats) VALUES(?,?,?,?,?)")) {
            stmt.setInt(1, movieId);
            stmt.setString(2, hall);
            stmt.setString(3, time);
            stmt.setDouble(4, price);
            stmt.setInt(5, total);
            stmt.executeUpdate();
            System.out.println("排片添加成功！");
        } catch (SQLException e) {
            System.err.println("添加排片失败: " + e.getMessage());
        }
    }

    public static void listSchedules() {
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT s.id,m.name,s.hall,s.time,s.price,s.total_seats FROM schedules s JOIN movies m ON s.movie_id=m.id")) {
            while (rs.next()) {
                System.out.println("场次ID:" + rs.getInt("id") + ", 电影:" + rs.getString("name") +
                        ", 影厅:" + rs.getString("hall") + ", 时间:" + rs.getString("time") +
                        ", 票价:" + rs.getDouble("price") + ", 总座位:" + rs.getInt("total_seats"));
            }
        } catch (SQLException e) {
            System.err.println("查询排片失败: " + e.getMessage());
        }
    }

    // ------------------ 前台功能实现 ------------------
    public static void sellTicket() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入场次ID: ");
        int scheduleId = Integer.parseInt(sc.nextLine());
        System.out.print("请输入座位号: ");
        String seat = sc.nextLine();
        String ticketId = UUID.randomUUID().toString();
        try (PreparedStatement stmt = conn.prepareStatement(
                "INSERT INTO tickets(ticket_id,schedule_id,seat,is_refunded) VALUES(?,?,?,0)")) {
            stmt.setString(1, ticketId);
            stmt.setInt(2, scheduleId);
            stmt.setString(3, seat);
            stmt.executeUpdate();
            System.out.println("售票成功！票号:" + ticketId);
        } catch (SQLException e) {
            System.err.println("售票失败: " + e.getMessage());
        }
    }

    public static void refundTicket() {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入电子票号: ");
        String ticketId = sc.nextLine();
        try (PreparedStatement stmt = conn.prepareStatement("UPDATE tickets SET is_refunded=1 WHERE ticket_id=?")) {
            stmt.setString(1, ticketId);
            int rows = stmt.executeUpdate();
            if (rows > 0) {
                System.out.println("退票成功！");
            } else {
                System.out.println("票号不存在！");
            }
        } catch (SQLException e) {
            System.err.println("退票失败: " + e.getMessage());
        }
    }

    // ------------------ 创建数据库表 ------------------
    public static void createTables() {
        try (Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE TABLE IF NOT EXISTS users (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "username TEXT UNIQUE, " +
                    "password TEXT, " +
                    "role TEXT, " +
                    "phone TEXT)");

            stmt.execute("CREATE TABLE IF NOT EXISTS movies (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "name TEXT, " +
                    "director TEXT, " +
                    "actor TEXT, " +
                    "description TEXT, " +
                    "duration INTEGER, " +
                    "rating REAL)");

            stmt.execute("CREATE TABLE IF NOT EXISTS schedules (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "movie_id INTEGER, " +
                    "hall TEXT, " +
                    "time TEXT, " +
                    "price REAL, " +
                    "total_seats INTEGER, " +
                    "FOREIGN KEY (movie_id) REFERENCES movies(id))");

            stmt.execute("CREATE TABLE IF NOT EXISTS tickets (" +
                    "ticket_id TEXT PRIMARY KEY, " +
                    "schedule_id INTEGER, " +
                    "seat TEXT, " +
                    "is_refunded INTEGER, " +
                    "FOREIGN KEY (schedule_id) REFERENCES schedules(id))");
        } catch (SQLException e) {
            System.err.println("表创建失败: " + e.getMessage());
        }
    }
}
